package com.meida.student.app.user.handler.pc;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.constants.CommonConstants;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusSubject;
import com.meida.module.bus.client.entity.BusTutorType;
import com.meida.module.bus.client.enums.*;
import com.meida.module.bus.provider.service.BusOrderAnswerService;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.bus.provider.service.BusSubjectService;
import com.meida.module.bus.provider.service.BusTutorTypeService;
import com.meida.module.bus.provider.utils.MyDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * 用户订单列表
 *
 * @author Administrator
 */
@Slf4j
@Component
public class PcUserOrderPageListHandler implements PageInterceptor<BusOrder> {

    @Autowired
    private BusOrderService busOrderService;

    @Autowired
    private BusSubjectService busSubjectService;

    @Autowired
    private BusTutorTypeService busTutorTypeService;

    @Autowired
    private BusOrderAnswerService orderAnswerService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public void prepare(CriteriaQuery<BusOrder> cq, PageParams pageParams, EntityMap params) {
        cq.clear();
        //请求来源
        Integer pageType = params.getInt("pageType", 0);
        //用户端我的订单筛选状态
        Integer orderDetailState = params.getInt("orderDetailState", null);
        cq.select(BusOrder.class, "orderId", "orderNo", "orderType", "subjectIds", "answerUserId", "tutorTypeId", "appointmentDate", "appointmentTime", "privateOrder", "durationTime", "orderState", "orderDescribe", "coverImg", "createTime");
        cq.select(BusSubject.class, "subjectTitle");
        cq.eq(BusOrder.class, "orderType");
        cq.eq(BusOrder.class, "deleted", 0);
        cq.eq(BusOrder.class, "userId", OpenHelper.getUserId());

        //最近订单index界面
        if (pageType.equals(1)) {
            //排除草稿
            cq.ne("orderState", -1);
        }
        //全部
        if (FlymeUtils.isEmpty(orderDetailState)) {
            cq.and(true, q -> {
                //作业无忧订单未支付的也显示
                q.and(true, q1 -> {
                    q1.ne("orderType", OrderTypeEnum.HomeWork.getValue());
                    q1.eq("payState", PayStateEnum.HavePay.getValue());
                });
                q.or().eq("orderType", OrderTypeEnum.HomeWork.getValue());
            });
        }
        cq.createJoin(BusSubject.class).setMainField("subjectId").setJoinField("subjectId");

        if (FlymeUtils.isNotEmpty(orderDetailState)) {
            //草稿
            if (orderDetailState == -1) {
                cq.eq(BusOrder.class, "orderState", -1);
            }
            //全部
            if (orderDetailState == OrderSearchStateEnum.orderDetailState0.getValue()) {
                cq.ne("orderState", -1);
            }
            if (orderDetailState == OrderSearchStateEnum.orderDetailState1.getValue()) {
                cq.and(true, q -> {
                    q.like("orderState", OrderStatePEnum.OrderState1.getValue());
                    q.or().like("orderState", OrderStateYEnum.OrderState1.getValue());
                });
            }
            //待出价
            if (orderDetailState == OrderSearchStateEnum.orderDetailState2.getValue()) {
                cq.eq("orderState", OrderStateZEnum.OrderState1.getValue());
            }
            //待解答((拍照提问/预约辅导))
            if (orderDetailState == OrderSearchStateEnum.orderDetailState3.getValue()) {
                cq.and(true, q -> {
                    q.like("orderState", OrderStatePEnum.OrderState2.getValue());
                    q.or().like("orderState", OrderStateYEnum.OrderState2.getValue());
                });
            }
            //待上课(预约辅导)
            if (orderDetailState == OrderSearchStateEnum.orderDetailState4.getValue()) {
                cq.eq("orderState", OrderStateYEnum.OrderState2.getValue());
            }
            //上课中(预约辅导)
            if (orderDetailState == OrderSearchStateEnum.orderDetailState5.getValue()) {
                cq.eq("orderState", OrderStateYEnum.OrderState3.getValue());
            }
            //已完成
            if (orderDetailState == OrderSearchStateEnum.orderDetailState6.getValue()) {
                cq.eq("orderState", "5");
            }
            //已取消
            if (orderDetailState == OrderSearchStateEnum.orderDetailState7.getValue()) {
                cq.eq("orderState", "0");
            }
            //已退款
            if (orderDetailState == OrderSearchStateEnum.orderDetailState8.getValue()) {
                cq.eq("orderState", "7");
            }
            //售后处理中
            if (orderDetailState == OrderSearchStateEnum.orderDetailState9.getValue()) {
                cq.eq("orderState", "6");
            }
        }
    }

    @Override
    public void complete(CriteriaQuery<BusOrder> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap entityMap : result) {
            Long orderId = entityMap.getLong("orderId");
            Long answerUserId = entityMap.getLong("answerUserId");
            String subjectIds = entityMap.get("subjectIds");
            String appointmentDate = entityMap.get("appointmentDate");
            List<String> subjectTitles = busSubjectService.selectSubjectTitles(subjectIds);
            entityMap.put("subjectTitles", subjectTitles);
            String orderState = entityMap.get("orderState");
            Integer orderType = entityMap.getInt("orderType");
            //订单类型转换
            String orderTypeDesc = busOrderService.getOrderTypeDesc(orderType);
            entityMap.put("orderTypeDesc", orderTypeDesc);
            //订单状态转换
            EntityMap convertOrderStateMap = busOrderService.convertOrderState(orderId, orderType, orderState);
            entityMap.putAll(convertOrderStateMap);

            Long tutorTypeId = entityMap.getLong("tutorTypeId");
            //辅导类型
            BusTutorType tutorType = busTutorTypeService.getById(tutorTypeId);
            if (FlymeUtils.isNotEmpty(tutorType)) {
                String tutorTypeName = tutorType.getTutorTypeName();
                Integer chargeType = tutorType.getChargeType();
                BigDecimal tutorPrice = tutorType.getTutorPrice();
                BigDecimal durationTime = entityMap.getBigDecimal("durationTime");
                if (chargeType.equals(1)) {
                    durationTime = durationTime.setScale(0, RoundingMode.HALF_UP);
                }
                String priceUnit = tutorType.getPriceUnit();
                String tutorTitle = MessageFormat.format("{0}(${1}/{2})", tutorTypeName, tutorPrice, priceUnit);
                entityMap.put("tutorTitle", tutorTitle);
                entityMap.put("durationTime", durationTime + priceUnit);
            }
            //是否私单
            Integer privateOrder = entityMap.getInt("privateOrder");
            if (privateOrder.equals(CommonConstants.ENABLED)) {
                if (orderState.equals("P1") || orderState.equals("Y1") || orderState.equals("Z1")) {
                    EntityMap orderAnswer = orderAnswerService.getOrderAnswerByOrderIdAndUserId(orderId, answerUserId);
                    Integer receiveState = orderAnswer.getInt("receiveState");
                    if (receiveState.equals(1)) {
                        entityMap.put("orderStateDesc", "待支付");
                    }
                }
            }

            //格式化显示日期
            Date createTime = entityMap.get("createTime");
            String targetTimezone = httpServletRequest.getHeader("targetTimezone");
            String showTime =DateUtils.formatFromTodayByTargetTimezone(createTime,targetTimezone);
            entityMap.put("showTime", showTime);
            String appointmentTime = entityMap.get("appointmentTime");
            if (FlymeUtils.isNotEmpty(appointmentDate)) {
                String appointmentDateTimeStr = appointmentDate + " " + appointmentTime + ":00";
                Date date = DateUtils.strToDate(appointmentDateTimeStr, "yyyy-MM-dd HH:mm:ss");
                Date newDate = MyDateUtils.convertTimezone(date, targetTimezone);
                String newAppointmentDate = DateUtils.formatDate(newDate, "yyyy-MM-dd");
                String newAppointmentTime = DateUtils.formatDate(newDate, "HH:mm");
                String dayOfWeek = DateUtils.getDayOfWeek(DateUtils.formatDate(newAppointmentDate));
                entityMap.put("dayOfWeek", dayOfWeek);
                entityMap.put("appointmentDate", newAppointmentDate);
                entityMap.put("appointmentTime", newAppointmentTime);
            }

        }
    }

}
